
 * @Author: ZHM zhuimin111@163.com
 * @Date: 2023-05-16 15:12:35
 * @LastEditors: g05047
 * @LastEditTime: 2023-05-30 14:00:30
 <template>
  <div class="expert-scoring">
    <el-row class="full-height">
      <el-col :span="(props.reviewTaskType== 2 ? 8 : 24)"
        class="full-height">
        <!-- 评分项区域  -->
        <el-scrollbar class="scrollbar-expert-scoring">
          <div class="scoring-list-area"
            v-loading="loading">
            <el-form ref="scoringItemsFormRef"
              v-if="dynamicValidateForm.scoringItems.length > 0"
              :model="dynamicValidateForm"
              label-width="auto">
              <el-card shadow="never"
                v-for="(scoringItem, index) in dynamicValidateForm.scoringItems"
                :key="index"
                :id="scoringItem.pfbzId"
                class="scoring-card">
                <template #header>
                  <div style="cursor: pointer;"
                    @click="handleScoringItemTitleClick(scoringItem)">
                    <span>
                      {{ index + 1 }}.{{ scoringItem.entryLev2 }}
                    </span>
                    <span v-if="scoringItem.scoreType == 1"
                      style="margin-left: 10px;">
                      ({{ scoringItem.scoreRange }} 分)
                    </span>
                    <span v-if="scoringItem.isOnevoteVeto == 1">
                      （涉及一票否决）
                    </span>
                  </div>
                  <div class="ant-card-extra">
                    <span v-if="scoringItem.report"
                      title="分析报表"
                      class="card-head-extra-icon"
                      @click.stop="handleScoringItemReport(scoringItem)">
                      <el-icon>
                        <Tickets />
                      </el-icon>
                    </span>
                    <span title="评审意见"
                      class="card-head-extra-icon"
                      @click.stop="scoringItemRemarkModelOpen(scoringItem)">
                      <el-icon>
                        <Tickets />
                      </el-icon>
                    </span>
                  </div>
                </template>
                <el-form-item label="评审内容:">
                  <span>{{ scoringItem.reviewDesc }}</span>
                </el-form-item>
                <el-form-item label="评审得分:"
                  :prop="`scoringItems.${index}.score`"
                  :rules="{
                       required: (scoringItem.scoreType != 4),
                       message: '评审得分不能为空',
                       trigger: ['blur', 'change'],
                      }">
                  <template v-if="scoringItem.scoreType == 1">
                    <el-input-number v-model="scoringItem.score"
                      :min="0"
                      :max="scoringItem.scoreRange"
                      @blur="scoringItemNumberChange" />
                  </template>
                  <template v-if="scoringItem.scoreType == 2">
                    <el-radio-group name="correctGroup" 
                      v-model="scoringItem.score">
                      <el-radio :label="'1'">是</el-radio>
                      <el-radio :label="'0'">否</el-radio>
                    </el-radio-group>
                  </template>
                </el-form-item>
                <el-form-item v-if="scoringItem.opinion"
                  label="评审意见:">
                  <span>{{ scoringItem.opinion }}</span>
                </el-form-item>
              </el-card>
            </el-form>
            <div class="empty-wrapper"
              v-else>
              <el-empty class="catalog-empty"
                description="empty" />
            </div>
          </div>
        </el-scrollbar>
      </el-col>
      <el-col :span="16"
        v-if="props.reviewTaskType==2">
        <!-- pdf区域  -->
        <div class="scoring-read-info">
          <el-tabs tab-position="right"
            v-model="activeName"
            class="operation-tabs"
            @change="handleContentTabsChange">
            <el-tab-pane label="项目实施方案"
              v-if="fileSrcLoaded"
              name="first"
              style="height: 100%;"
              v-loading="buildSchemeLoaded">
              <template #label>
                项<br>目<br>实<br>施<br>方<br>案
              </template>
              <div :class="['scoring-content-html-wrapper']">
                <!-- 功能面板区域 -->
                <!-- <div v-if="ratingContent"
                                  class="content-tools-hover-wrapper"
                                  @mouseover="toolsMouseover"
                                  @mouseleave="toolsMouseleave">
                                  <div class="content-tools-main-wrapper"
                                    v-show="htmlToolsVisible">
                                    <div class="tools-left">
                                      <div class="tool-item-catalog"
                                        style="width: 100px;">
                                        <span>共 1 页</span>
                                      </div>
                                    </div>
                                    <div class="tools-right">
                                      <div class="tool-item-catalog"
                                        @click="reloadOpen">
                                        <span title="重新打开">
                                          <el-icon>
                                            <FolderOpened />
                                          </el-icon>
                                        </span>
                                      </div>
                                      <div class="tool-item-catalog"
                                        @click="download">
                                        <span title="下载">
                                          <el-icon>
                                            <Download />
                                          </el-icon>
                                        </span>
                                      </div>
                                    </div>
                                  </div>
                                </div> -->
                <!-- Pdf区域 -->
                <report-pdf-preview ref="reportPdfXMSSViewRef"
                  title="项目实施方案"
                  :fileId="implemenId"
                  :attachmentType="1"
                  :position="scoringItemPosition">
                </report-pdf-preview>
              </div>
            </el-tab-pane>
            <el-tab-pane label="财务评价报告"
              v-if="fileSrcLoaded"
              name="second"
              style="height:100%">
              <template #label>
                财<br>务<br>评<br>价<br>报<br>告
              </template>
              <report-pdf-preview ref="reportPdfViewRef"
                title="财务评价报告"
                :fileId="reportPdfId"
                :attachmentType="1"
                :position="scoringItemPosition">
              </report-pdf-preview>
            </el-tab-pane>
            <el-tab-pane label="法律意见书"
              v-if=" fileSrcLoaded"
              name="third">
              <template #label>
                法<br>律<br>意<br>见<br>书
              </template>
              <report-pdf-preview ref="lawBookPdfViewRef"
                title="法律意见书"
                :fileId="lawBookPdfId"
                :attachmentType="2"
                :position="scoringItemPosition">
              </report-pdf-preview>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
  <!--  评分卡  -->
  <div class="scoring-card-wrapper">
    <div class="scoring-item-area">
      <div class="scoring-card-title"
        @click="triggerScoringCard">
        <span>
          <el-icon style="margin-right: 5px;">
            <Top v-if="!ratingCardVisible" />
            <Bottom v-if="ratingCardVisible" />
          </el-icon>
          评分卡
        </span>
      </div>
      <div class="scoring-card-info"
        v-show="ratingCardVisible">
        <div class="scoring-item-ul">
          <ul v-for="(scoringItem, index) in cardData"
            :key="index"
            :class="['li-item', IsUtils.isNotEmpty(scoringItem.score) ? 'active' : ''] "
            @click="handleScoringScroll(scoringItem)">
            {{ index + 1 }}
          </ul>
        </div>
      </div>
    </div>
  </div>
  <!-- 备注弹窗 -->
  <item-remark-modal ref="itemRemarkModalRef"
    v-model:visible="itemRemarkModelVisible"
    :scoringItem="editScoringItem"
    :ok="scoringItemRemarkModelOk">
  </item-remark-modal>
</template>

<script setup>
import { Tickets,Top,Bottom } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref, watchEffect } from "vue"
import ItemRemarkModal from "./ItemRemarkModal.vue"
import ReportPdfPreview from "./ReportPdfPreview.vue"
import MathUtils from '@/utils/math-utils'
import IsUtils from '@/utils/is-utils.js'
import { useOnlineApi,useFileApi } from '@/api/index';
const { getDebtTZqglPfbzByProId } = useOnlineApi();
const { getOnlineUploadFiles } = useFileApi();
const loading = ref(true);
//pdf 预览
let activeName = ref('first');
const buildSchemeLoaded = ref(false);
const props = defineProps({
  proId: {
    type: String,
    default: " "
  },
  reviewTaskType: {
    type: Number,
    default: " "
  },
  activityTaskId: {
    type: String,
    default: " "
  },
  taskId: {
    type: String,
    default: " "
  },
  applyId: {
    type: String,
    default: " "
  },
  setRatingGrade: {
    type: [Promise, Function],
    default: () => {
      return new Promise(resolve => resolve())
    }
  },
  setTotalScore: {
    type: [Promise, Function],
    default: () => {
      return new Promise(resolve => resolve())
    }
  }
})
watch(() => [props.taskId, props.applyId], ([v1, v2]) => {
  getRatingItemList();
  getOnlineUploadList();
}, { deep: true })

// onMounted(() => {
//   if (props.taskId && props.applyId) {
//     //获取评审规则列表
//     getRatingItemList();
//     // 获取附件列表
//     getOnlineUploadList();
//   }
// })
// 表单数据项目
let dynamicValidateForm = reactive({
  isMatchCondition: "",
  remark: "",
  scoringItems: []
})
let cardData = ref('')
const getRatingItemList = async () => {
  loading.value = false
  const deleteParams = { applyId: props.applyId, taskId: props.taskId }
  const result = await getDebtTZqglPfbzByProId(deleteParams)
  const { data, code, msg } = result
  if (code === 200) {
    let ItemList = data
    let scoringData = []
    let cardList = []
    let totalScore = 0
    let totalRatingScore = 0
    ItemList.forEach(scoringItem => {
      let list = scoringItem.onlineViewVoList;
      if (list && list.length > 0) {
        list = list.map((item) => {
          if (item.scoreType == 1) {
            totalScore += item.scoreRange
            let score = item.score
            if (typeof score === "string") {
              score = Number(score)
              item.score = score
              totalRatingScore += score
            }
          }
          item['report'] = REPORT_URL[item.reviewItem]
          cardList.push(item)
          return item
        })
      }
    })
    props.setRatingGrade(totalRatingScore)
    props.setTotalScore(totalScore)
    dynamicValidateForm.scoringItems = cardList
    cardData.value = cardList
  } else {
    ElMessage({ message: `${msg}`, type: "error" });
  }
}
//获取pdf列表
const fileSrcLoaded = ref(false)
let implemenId = ref('')
let reportPdfId = ref('');
let lawBookPdfId = ref('')
const getOnlineUploadList = async () => {
  if (props.reviewTaskType == 1) {
    activeName.value = 'four'
  } else {
    activeName.value = 'first'
    fileSrcLoaded.value = false
    const deleteParams = {
      busiId: props.proId,
      busiType: 'ET001'
    }
    const result = await getOnlineUploadFiles(deleteParams)
    const { data, code, msg } = result
    if (code == 200) {
      if (data && data.length > 0) {
        implemenId.value = data[0].fileId
        reportPdfId.value = data[1].fileId
        lawBookPdfId.value = data[2].fileId
        fileSrcLoaded.value = true
      } else {
        fileSrcLoaded.value = false
      }
    }
  }

}

// 分析报表点击
const handleScoringItemReport = (scoringItem) => {
  const { report } = scoringItem
  if (report) {
    // window.open(report, '_blank')
  }
}
/** 评分项的备注modal相关方法 --- start */
// 编辑中的评分项
const itemRemarkModalRef = ref(null)
const itemRemarkModelVisible = ref(false)
let editScoringItem = reactive({})
const REPORT_URL = {
  '收益与融资平衡情况': 'http://ds.dasytech.com:8983/page/plat/query/reportQuery.jsp?code=bda_fwpt_t_o_bond_xmmx_fqh_ftx&token_md=md#'
}
/** 评分项的备注modal相关方法 --- start */
const scoringItemRemarkModelOpen = (scoringItem) => {
  editScoringItem.value = scoringItem
  itemRemarkModelVisible.value = true
}
const scoringItemRemarkModelOk = (remark) => {
  editScoringItem.value.opinion = remark
  itemRemarkModelVisible.value = false
}

/** 保存评分内容校验 */
const getPreviewScoingItemsData = () => {
  const { isMatchCondition } = dynamicValidateForm
  let totalRemark = ""
  if (cardData.value && cardData.value.length > 0) {
    const submitScoreList = cardData.value.map((item) => {
      if (item.opinion && !isMatchCondition) {
        totalRemark += item.opinion
      }
      return {
        "ruleId": item.pfbzId,
        "scoreType": item.scoreType,
        "score": item.score,
        "opinion": item.opinion
      }
    })
    return {
      "reviewTaskType": props.reviewTaskType,
      "activityTaskId": props.activityTaskId,
      "applyId": props.applyId,
      "taskId": props.taskId,
      "isMatchCondition": isMatchCondition,
      "expertOpinion": totalRemark,
      "scoreItemList": submitScoreList
    }
  }
}
/** 输入分数发生变化 */
const scoringItemNumberChange = (value) => {
  let totalRatingScore = 0
  const { scoringItems } = dynamicValidateForm
  scoringItems.forEach(element => {
    if (element.scoreType == 1) {
      let score = element.score
      if (typeof score === "string")
        score = parseFloat.score
      totalRatingScore = MathUtils.mathAdd(totalRatingScore, Number(score))
    }
  })
  props.setRatingGrade(totalRatingScore.toFixed(2))
}
// 评分项选择定位信息
let scoringItemPosition = ref('');
const reportPdfXMSSViewRef = ref(null)
/** 评分项标题点击 */
const handleScoringItemTitleClick = (scoringItem) => {
  scoringItemPosition.value = activeName.value
  activeName.value = 'first'
  //定位到建设方案
  const { filePlace } = scoringItem
  if (filePlace) {
    reportPdfXMSSViewRef.value.toPage(filePlace)
  }
}
// const reloadOpen = () => {
//   reportPdfXMSSViewRef.value.reloadOpen()
// }
// const download = () => {
//   reportPdfXMSSViewRef.value.download()
// }

/** 内容展示页tab切换 */
const handleContentTabsChange = () => {
  if (activeName.value == 'first') {
    reportPdfXMSSViewRef.value.toPage(1)
  }
}
/** 滚动到评分项 */
const handleScoringScroll = (scoringItem) => {
  const { pfbzId } = scoringItem
  if (pfbzId) {
    document.getElementById(pfbzId).scrollIntoView({
      behavior: "smooth", //smooth:平滑，auto：直接定位
      block: "start"
    });
  }
}
const ratingCardVisible = ref(false)
/** 答题卡显示隐藏 */
const triggerScoringCard = () => {
  ratingCardVisible.value = !ratingCardVisible.value
}

/** 工具栏鼠标移入 */
// 目录是否出现
let buildCatalogVisible = ref(false);
let htmlToolsVisible = ref(false);
const toolsMouseover = () => {
  if (!buildCatalogVisible.value) {
    htmlToolsVisible.value = true
  }
}
/** 工具栏鼠标移出 */
const toolsMouseleave = () => {
  if (!buildCatalogVisible.value) {
    htmlToolsVisible.value = false
  }
}
const scoringItemsFormRef = ref(null);
const submitScoringItemsForm = () => {
  const { isMatchCondition } = dynamicValidateForm
  return new Promise(resolve => {
    if (cardData.value && cardData.value.length > 0) {
      scoringItemsFormRef.value.validate(valid => {
        let returnData = { valid: valid }
        if (valid) {
          let totalRemark = ""
          const submitScoreList = cardData.value.map((item) => {
            if (item.opinion && !isMatchCondition) {
              totalRemark += item.opinion
            }
            return {
              "ruleId": item.pfbzId,
              "scoreType": item.scoreType,
              "score": item.score,
              "opinion": item.opinion
            }
          })
          // 回显数据
          if (!isMatchCondition) {
            dynamicValidateForm.remark = totalRemark
          }
          returnData["scoreList"] = submitScoreList
          returnData["dynamicForm"] = dynamicValidateForm
        }
        resolve(returnData)
      })
    } else {
      ElMessage("暂无评分项，无法审批！")
      resolve({
        valid: false
      })
    }
  })

}

const resertData = () => {
  dynamicValidateForm.isMatchCondition = ""
  dynamicValidateForm.remark = ""
  // dynamicValidateForm.scoringItems = []
}

// 对外暴露方法
defineExpose({
  getPreviewScoingItemsData,
  submitScoringItemsForm,
  resertData,
  getRatingItemList,
  getOnlineUploadList
})

</script>

<style lang="scss" scoped>
@import "./scss/expert-scoring-scoped.scss";

.jump_page {
  color: #1890ff;

  &:hover {
    text-decoration: underline;
  }
}
</style>

<style lang="scss">
@import "./scss/expert-scoring.scss";
</style>
